<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收运人员" prop="collectorId">
        <el-input v-model="queryParams.collectorId" placeholder="请输入收运人员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" style="width: 200px" placeholder="请选择状态" clearable>
          <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker
          clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['order:userorder:add']"
        >新增</el-button
      >
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table border stripe v-loading="loading" :data="userorderList">
      <el-table-column
        label="订单唯一编号"
        align="center"
        prop="orderNo"
        width="120"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true" />
      <el-table-column label="图片" align="center" prop="images" width="100" v-if="columns[8].visible">
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="置信度"
        align="center"
        prop="confidence"
        v-if="columns[9].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="类别"
        align="center"
        prop="labels"
        v-if="columns[10].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          {{ labelMap[scope.row.labels] || scope.row.labels }}
        </template>
      </el-table-column>
      <el-table-column
        label="重量"
        align="center"
        prop="weight"
        v-if="columns[4].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="单价"
        align="center"
        prop="unitPrice"
        v-if="columns[5].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="积分"
        align="center"
        prop="totalValue"
        v-if="columns[6].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="收运人员"
        align="center"
        prop="collectorId"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" v-if="columns[7].visible">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="订单地址"
        align="center"
        prop="address"
        v-if="columns[13].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="100"
        v-if="columns[11].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改订单对话框 -->
    <el-dialog
      class="adding-order__container"
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      destroy-on-close>
      <el-form ref="userorderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <image-upload v-model="form.images" @upload-success="handleUploadSuccess" />
        </el-form-item>
        <el-form-item label="类别" prop="label">
          <el-input v-model="form.labels" placeholder="请上传图片" readonly />
        </el-form-item>
        <el-form-item label="置信度" prop="confidence">
          <el-input v-model="form.confidence" placeholder="请上传图片" readonly />
        </el-form-item>
        <el-form-item label="订单地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入订单地址" />
        </el-form-item>
        <TMap @locationUpdate="handleLocationUpdate" :location="{address:form.address}" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Userorder">
import { listUserorder, addUserorder, updateUserorder } from '@/api/order/userorder'
import useUserStore from '@/store/modules/user'
import TMap from '@/components/TMap/index.vue'
const { proxy } = getCurrentInstance()
const { order_status } = proxy.useDict('order_status')

const userorderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref('')

const labelMap = {
  PAPER: '黄纸壳',
  PAPER_BOOK: '书本/报纸',
  PLASTIC_PET: '矿泉水瓶',
  METAL_AL: '铝制品',
  METAL_CU: '铜制品'
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    collectorId: null,
    status: null,
    createdAt: null
  },
  rules: {
    weight: [{ required: true, message: '重量不能为空', trigger: 'blur' }]
    // images: [{ required: true, message: '图片不能为空', trigger: 'blur' }]
  },
  //表格展示列
  columns: [
    { key: 0, label: '', visible: true },
    { key: 1, label: '订单唯一编号', visible: true },
    { key: 2, label: '客户', visible: true },
    { key: 3, label: '收运人员', visible: true },
    { key: 4, label: '重量', visible: true },
    { key: 5, label: '单价', visible: true },
    { key: 6, label: '价值', visible: true },
    { key: 7, label: '状态', visible: true },
    { key: 8, label: '图片', visible: true },
    { key: 9, label: '置信度', visible: true },
    { key: 10, label: '类别', visible: true },
    { key: 11, label: '创建时间', visible: true },
    { key: 12, label: '更新时间', visible: true },
    { key: 13, label: '订单地址', visible: true }
  ],
  storedLabel: null, // 存储类别
  storedConfidence: null // 存储置信度
})

const { queryParams, form, rules, columns, storedLabel, storedConfidence } = toRefs(data)
/** 查询订单列表 */
function getList() {
  loading.value = true
  listUserorder(queryParams.value).then(response => {
    userorderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    clientId: null,
    collectorId: null,
    weight: null,
    unitPrice: null,
    totalValue: null,
    status: null,
    images: null,
    confidence: null,
    labels: null,
    createdAt: null,
    updatedAt: null,
    address: null
  }
  proxy.resetForm('userorderRef')
}

function handleUploadSuccess({ label, confidence }) {
  // 存储 label 和 confidence
  storedLabel.value = label[0] // 类别
  storedConfidence.value = confidence[0] // 置信度

  form.value.labels = label[0]
  form.value.confidence = confidence[0]
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

const userStore = useUserStore()
/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 自动填充当前用户ID到clientId
  form.value.clientId = userStore.id
  form.value.status = 'pending'
  open.value = true
  title.value = '添加订单'
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['userorderRef'].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateUserorder(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addUserorder(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
function handleLocationUpdate(location) {
  if(location.formatted_addresses){
    const { standard_address, recommend } = location.formatted_addresses
    form.value.address = `${standard_address} ${recommend}`
  }
  form.value.latitude = location.location.lat
  form.value.longitude = location.location.lng
}
getList()
</script>
<style>
.adding-order__container .el-dialog__body {
  height: calc(80vh);
  overflow: auto;
}
</style>
